"""
智能更新API v2 - 基于新的核心服务架构
"""

import logging
import threading
from datetime import datetime
from flask import Blueprint, request, current_app

from ...middleware import ResponseFormatter
from ...services.core import (
    WorkflowOrchestrator, ImageVerificationService, 
    ContainerManagementService, PatternMatchingService,
    StepType, StepContext
)
from ...services.integrations import LWXPlatformService
from ...services.image_update_status import get_status_manager


logger = logging.getLogger(__name__)
intelligent_update_bp = Blueprint('intelligent_update_v2', __name__, url_prefix='/api/v2/intelligent-updates')

# 全局服务实例（在实际使用中应该通过依赖注入）
_orchestrator = None
_lwx_service = None


def get_orchestrator():
    """获取工作流编排器实例"""
    global _orchestrator
    if _orchestrator is None:
        status_manager = get_status_manager()
        _orchestrator = WorkflowOrchestrator(
            verification_service=ImageVerificationService(),
            container_service=ContainerManagementService(),
            pattern_service=PatternMatchingService(),
            status_manager=status_manager
        )
    return _orchestrator


def get_lwx_service():
    """获取LWX平台服务实例"""
    global _lwx_service
    if _lwx_service is None:
        report_url = current_app.config.get('DEVICE_REPORT_URL')
        aes_key = current_app.config.get('DEVICE_REPORT_AES_KEY')
        _lwx_service = LWXPlatformService(report_url, aes_key)
    return _lwx_service


@intelligent_update_bp.route('/lwx-parse', methods=['POST'])
def lwx_parse_step():
    """
    步骤1: LWX平台数据解析
    从LWX平台获取学校信息和基础镜像版本
    """
    try:
        data = request.get_json() or {}
        trigger_sync = data.get('trigger_sync', False)  # 手动模式默认不触发同步
        
        logger.info("执行步骤1: LWX平台数据解析")
        
        # 获取LWX服务
        lwx_service = get_lwx_service()
        
        # 收集设备信息
        device_info = lwx_service.collect_device_info()
        if not device_info:
            return ResponseFormatter.error(
                message="设备信息收集失败",
                error_code="DEVICE_INFO_COLLECTION_FAILED"
            )
        
        # 上报到LWX平台
        report_result = lwx_service.report_device_info(device_info, trigger_sync)
        if not report_result.success:
            return ResponseFormatter.error(
                message=f"LWX平台数据解析失败: {report_result.message}",
                error_code="LWX_PLATFORM_ERROR"
            )
        
        # 提取学校配置
        school_config = report_result.details.get('school_config')
        if not school_config:
            return ResponseFormatter.error(
                message="未能从LWX平台获取学校配置信息",
                error_code="SCHOOL_CONFIG_MISSING"
            )
        
        # 构建模式匹配服务以获取更多信息
        pattern_service = PatternMatchingService()
        full_image_url = pattern_service.build_full_image_url(school_config.base_image)
        compose_file = pattern_service.select_compose_file(school_config.base_image)
        container_name = pattern_service.extract_container_name_from_compose(compose_file)
        
        result_data = {
            "school_name": school_config.school_name,
            "school_id": school_config.school_id,
            "base_image": school_config.base_image,
            "full_image_url": full_image_url,
            "compose_file": compose_file,
            "container_name": container_name,
            "pattern_info": pattern_service.get_pattern_info(school_config.base_image)
        }
        
        return ResponseFormatter.success(
            message="LWX平台数据解析完成",
            data=result_data
        )
        
    except Exception as e:
        logger.error(f"LWX平台数据解析步骤失败: {e}")
        return ResponseFormatter.error(
            message=f"LWX平台数据解析步骤失败: {str(e)}",
            error_code="LWX_PARSE_STEP_ERROR"
        )


@intelligent_update_bp.route('/image-verify', methods=['POST'])
def image_verification_step():
    """
    步骤2: 智能镜像版本校验
    检查本地镜像版本和容器状态，决定后续操作类型
    """
    try:
        data = request.get_json() or {}
        
        # 从请求中获取必要参数
        full_image_url = data.get('full_image_url')
        container_name = data.get('container_name')
        
        if not full_image_url or not container_name:
            return ResponseFormatter.error(
                message="缺少必需参数: full_image_url 或 container_name",
                error_code="MISSING_PARAMETERS"
            )
        
        logger.info(f"执行步骤2: 智能镜像版本校验 - 镜像: {full_image_url}, 容器: {container_name}")
        
        # 获取镜像校验服务
        verification_service = ImageVerificationService()
        
        # 执行智能校验
        verification_result = verification_service.verify_image_status(full_image_url, container_name)
        
        result_data = {
            "verification_result": {
                "needs_action": verification_result.needs_action,
                "action_type": verification_result.action_type.value,
                "reason": verification_result.reason
            },
            "local_image_info": verification_result.local_image_info.__dict__ if verification_result.local_image_info else None,
            "container_info": verification_result.container_info.__dict__ if verification_result.container_info else None,
            "next_steps": {
                "skip_pull": verification_result.action_type.value in ['none', 'restart'],
                "skip_rebuild": verification_result.action_type.value == 'none'
            }
        }
        
        return ResponseFormatter.success(
            message=f"镜像版本校验完成: {verification_result.reason}",
            data=result_data
        )
        
    except Exception as e:
        logger.error(f"镜像版本校验步骤失败: {e}")
        return ResponseFormatter.error(
            message=f"镜像版本校验步骤失败: {str(e)}",
            error_code="IMAGE_VERIFY_STEP_ERROR"
        )


@intelligent_update_bp.route('/conditional-pull', methods=['POST'])
def conditional_pull_step():
    """
    步骤3: 条件性镜像拉取
    仅在需要更新或重建时执行镜像拉取
    """
    try:
        data = request.get_json() or {}
        
        action_type = data.get('action_type')
        full_image_url = data.get('full_image_url')
        
        if not action_type or not full_image_url:
            return ResponseFormatter.error(
                message="缺少必需参数: action_type 或 full_image_url",
                error_code="MISSING_PARAMETERS"
            )
        
        logger.info(f"执行步骤3: 条件性镜像拉取 - 操作类型: {action_type}")
        
        # 检查是否需要拉取镜像
        if action_type in ['update', 'rebuild']:
            from ...services.integrations import DockerService
            docker_service = DockerService()
            
            # 执行镜像拉取
            pull_result = docker_service.pull_image(full_image_url)
            
            if not pull_result.success:
                return ResponseFormatter.error(
                    message=f"镜像拉取失败: {pull_result.message}",
                    error_code="IMAGE_PULL_FAILED"
                )
            
            return ResponseFormatter.success(
                message=f"镜像拉取成功: {full_image_url}",
                data={
                    "action_type": action_type,
                    "pulled_image": full_image_url,
                    "pull_details": pull_result.details
                }
            )
        else:
            # 无需拉取镜像
            return ResponseFormatter.success(
                message=f"无需拉取镜像，操作类型为: {action_type}",
                data={
                    "action_type": action_type,
                    "skipped": True,
                    "reason": f"操作类型 {action_type} 不需要拉取新镜像"
                }
            )
            
    except Exception as e:
        logger.error(f"条件性镜像拉取步骤失败: {e}")
        return ResponseFormatter.error(
            message=f"条件性镜像拉取步骤失败: {str(e)}",
            error_code="CONDITIONAL_PULL_STEP_ERROR"
        )


@intelligent_update_bp.route('/container-rebuild', methods=['POST'])
def container_rebuild_step():
    """
    步骤4: 智能容器重建
    根据校验结果执行相应的容器操作
    """
    try:
        data = request.get_json() or {}
        
        # 获取必要参数
        action_type = data.get('action_type')
        container_name = data.get('container_name')
        full_image_url = data.get('full_image_url')
        school_name = data.get('school_name', 'Unknown')
        
        if not all([action_type, container_name, full_image_url]):
            return ResponseFormatter.error(
                message="缺少必需参数: action_type, container_name 或 full_image_url",
                error_code="MISSING_PARAMETERS"
            )
        
        logger.info(f"执行步骤4: 智能容器重建 - 操作类型: {action_type}")
        
        # 获取容器管理服务
        container_service = ContainerManagementService()
        
        # 构建容器配置
        from ...services.core.types import ContainerConfig, ActionType
        
        container_config = ContainerConfig(
            image_url=full_image_url,
            container_name=container_name,
            school_name=school_name,
            ports={"8080": "8080"},  # 默认端口映射
            environment={
                "SCHOOL_NAME": school_name,
                "IMAGE_VERSION": full_image_url.split('/')[-1]
            }
        )
        
        # 执行相应操作
        action_enum = ActionType(action_type)
        operation_result = container_service.execute_action(
            action_enum, 
            container_name, 
            container_config
        )
        
        if operation_result.success:
            return ResponseFormatter.success(
                message=f"容器操作完成: {operation_result.message}",
                data={
                    "action_type": action_type,
                    "container_name": container_name,
                    "operation_details": operation_result.details
                }
            )
        else:
            return ResponseFormatter.error(
                message=f"容器操作失败: {operation_result.message}",
                error_code="CONTAINER_OPERATION_FAILED",
                data={
                    "action_type": action_type,
                    "container_name": container_name,
                    "error_details": operation_result.error
                }
            )
            
    except Exception as e:
        logger.error(f"智能容器重建步骤失败: {e}")
        return ResponseFormatter.error(
            message=f"智能容器重建步骤失败: {str(e)}",
            error_code="CONTAINER_REBUILD_STEP_ERROR"
        )


@intelligent_update_bp.route('/complete-workflow', methods=['POST'])
def complete_workflow():
    """
    完整工作流执行（自动模式）
    执行完整的4步骤智能更新流程
    """
    try:
        data = request.get_json() or {}
        force_update = data.get('force_update', False)
        
        logger.info("开始执行完整智能更新工作流")
        
        # 获取工作流编排器
        orchestrator = get_orchestrator()
        
        # 执行LWX平台数据解析
        lwx_service = get_lwx_service()
        device_info = lwx_service.collect_device_info()
        
        if not device_info:
            return ResponseFormatter.error(
                message="设备信息收集失败",
                error_code="DEVICE_INFO_COLLECTION_FAILED"
            )
        
        # 上报并获取学校配置
        report_result = lwx_service.report_device_info(device_info, trigger_sync=True)
        if not report_result.success:
            return ResponseFormatter.error(
                message=f"LWX平台交互失败: {report_result.message}",
                error_code="LWX_PLATFORM_ERROR"
            )
        
        school_config = report_result.details.get('school_config')
        if not school_config:
            return ResponseFormatter.error(
                message="未能获取学校配置",
                error_code="SCHOOL_CONFIG_MISSING"
            )
        
        # 在后台线程中执行完整工作流
        def background_workflow():
            try:
                workflow_result = orchestrator.execute_intelligent_update(
                    school_config.school_name,
                    school_config.base_image
                )
                logger.info(f"工作流执行完成: {workflow_result.success}")
            except Exception as e:
                logger.error(f"后台工作流执行失败: {e}")
        
        # 启动后台线程
        workflow_thread = threading.Thread(target=background_workflow)
        workflow_thread.daemon = True
        workflow_thread.start()
        
        return ResponseFormatter.success(
            message="智能更新工作流已启动",
            data={
                "school_name": school_config.school_name,
                "base_image": school_config.base_image,
                "workflow_started": True,
                "started_at": datetime.now().isoformat()
            }
        )
        
    except Exception as e:
        logger.error(f"完整工作流执行失败: {e}")
        return ResponseFormatter.error(
            message=f"完整工作流执行失败: {str(e)}",
            error_code="COMPLETE_WORKFLOW_ERROR"
        )